package com.zz.common.handle.executor;

import com.zz.common.annotation.Executor;
import com.zz.common.config.Config;
import com.zz.common.enums.MessageType;
import com.zz.common.protocol.TunnelProtocol;

import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 消息处理器工厂方法
 */
public class MessageExecutorFactory {
    private static final Map<MessageType, MessageExecutor> messageExecutorMap = new ConcurrentHashMap<>();

    static {
        ServiceLoader<MessageExecutor> executors = ServiceLoader.load(MessageExecutor.class);
        for (MessageExecutor executor : executors) {
            Executor annotation = executor.getClass().getAnnotation(Executor.class);
            if (Objects.isNull(annotation)) {
                continue;
            }
            Class<? extends TunnelProtocol> protocol = annotation.protocol();
            if (!Config.getInstance().getProtocol().equals(protocol)) {
                continue;
            }
            MessageType msgType = annotation.msgType();
            if (Objects.isNull(msgType) || msgType.equals(MessageType.EMPTY_TYPE)) {
                continue;
            }
            messageExecutorMap.put(msgType, executor);
        }
    }

    public static MessageExecutor getMessageExecutor(MessageType messageType) {
        return messageExecutorMap.get(messageType);
    }
}
